# 短信服务配置文件

from typing import Dict, Any
import aiohttp
from django.conf import settings
import logging
import requests  # 添加同步请求库

logger = logging.getLogger(__name__)


class SMSClient:
    """短信客户端"""

    def __init__(self):
        # 获取阿里云配置，如果不存在则使用默认值
        aliyun_config = getattr(settings, 'ALIYUN_SMS_CONFIG', {})
        self.access_key_id = aliyun_config.get('access_key_id', '')
        self.access_key_secret = aliyun_config.get('access_key_secret', '')
        self.sign_name = aliyun_config.get('sign_name', '')
        self.template_code = aliyun_config.get('template_code', '')
        self.endpoint = 'https://dysmsapi.aliyuncs.com'

    async def send_sms(self, phone_number: str, template_param: Dict[str, Any]) -> bool:
        """异步发送短信"""
        try:
            # 测试模式下不实际发送短信
            from apps.core.services.verification_service import VerificationService
            config = VerificationService.get_config()

            if config.get('TEST_MODE', False):
                logger.info(f"测试模式: 向 {phone_number} 发送验证码 {template_param.get('code')}")
                return True

            # 检查必要的配置是否存在
            if not all([self.access_key_id, self.access_key_secret, self.sign_name, self.template_code]):
                logger.error("阿里云短信配置不完整")
                return False

            async with aiohttp.ClientSession() as session:
                # 构建请求参数
                params = {
                    'PhoneNumbers': phone_number,
                    'SignName': self.sign_name,
                    'TemplateCode': self.template_code,
                    'TemplateParam': str(template_param),
                    'AccessKeyId': self.access_key_id,
                    # 其他阿里云SMS API需要的参数
                }

                async with session.post(self.endpoint, data=params) as response:
                    result = await response.json()
                    success = result.get('Code') == 'OK'

                    # 记录发送结果
                    await self._log_sms_result(phone_number, success, result)

                    return success

        except Exception as e:
            logger.error(f"发送短信失败: {str(e)}")
            await self._log_sms_error(phone_number, str(e))
            return False

    async def _log_sms_result(self, phone: str, success: bool, result: Dict):
        """异步记录短信发送结果"""
        from .models import SMSLog
        from django.utils import timezone

        try:
            await SMSLog.objects.acreate(
                phone_number=phone,
                send_status=success,
                message_id=result.get('RequestId'),
                response_code=result.get('Code'),
                response_message=result.get('Message'),
                sent_at=timezone.now()
            )
        except Exception as e:
            logger.error(f"记录短信日志失败: {str(e)}")

    async def _log_sms_error(self, phone: str, error: str):
        """异步记录短信发送错误"""
        from .models import SMSLog
        from django.utils import timezone

        try:
            await SMSLog.objects.acreate(
                phone_number=phone,
                send_status=False,
                response_message=error,
                sent_at=timezone.now()
            )
        except Exception as e:
            logger.error(f"记录错误日志失败: {str(e)}")

    def send_sms_sync(self, phone_number: str, template_param: Dict[str, Any]) -> bool:
        """同步发送短信"""
        try:
            # 测试模式下不实际发送短信
            from apps.core.services.verification_service import VerificationService
            config = VerificationService.get_config()

            if config.get('TEST_MODE', False):
                logger.info(f"测试模式: 向 {phone_number} 发送验证码 {template_param.get('code')}")
                return True

            # 检查必要的配置是否存在
            if not all([self.access_key_id, self.access_key_secret, self.sign_name, self.template_code]):
                logger.error("阿里云短信配置不完整")
                return False

            # 构建请求参数
            params = {
                'PhoneNumbers': phone_number,
                'SignName': self.sign_name,
                'TemplateCode': self.template_code,
                'TemplateParam': str(template_param),
                'AccessKeyId': self.access_key_id,
                # 其他阿里云SMS API需要的参数
            }

            response = requests.post(self.endpoint, data=params)
            result = response.json()
            success = result.get('Code') == 'OK'

            # 记录发送结果
            self._log_sms_result_sync(phone_number, success, result)

            return success

        except Exception as e:
            logger.error(f"发送短信失败: {str(e)}")
            self._log_sms_error_sync(phone_number, str(e))
            return False

    def _log_sms_result_sync(self, phone: str, success: bool, result: Dict):
        """同步记录短信发送结果"""
        from .models import SMSLog
        from django.utils import timezone

        try:
            SMSLog.objects.create(
                phone_number=phone,
                send_status=success,
                message_id=result.get('RequestId'),
                response_code=result.get('Code'),
                response_message=result.get('Message'),
                sent_at=timezone.now()
            )
        except Exception as e:
            logger.error(f"记录短信日志失败: {str(e)}")

    def _log_sms_error_sync(self, phone: str, error: str):
        """同步记录短信发送错误"""
        from .models import SMSLog
        from django.utils import timezone

        try:
            SMSLog.objects.create(
                phone_number=phone,
                send_status=False,
                response_message=error,
                sent_at=timezone.now()
            )
        except Exception as e:
            logger.error(f"记录错误日志失败: {str(e)}")
